package com.zzy.algorithm.stack;

import java.util.Stack;

/**
 * LeetCode - 232 : 用栈实现队列
 *
 * 请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作（push、pop、peek、empty）
 */
public class Q16_RealizeQueueWithStack {

    public static void main(String[] args) {
        MyQueue myQueue = new MyQueue();
        myQueue.push(1);
        myQueue.push(2);
        myQueue.push(3);

        System.out.println("myQueue.peek() = " + myQueue.peek());
        System.out.println("myQueue.pop() = " + myQueue.pop());
        System.out.println("myQueue.pop() = " + myQueue.pop());
        System.out.println("myQueue.pop() = " + myQueue.pop());
    }

    static class MyQueue {

        Stack<Integer> inStack = new Stack<>();
        Stack<Integer> outStack = new Stack<>();

        public MyQueue() {

        }

        public void push(int x) {
            inStack.push(x);
        }

        public int pop() {
            if(outStack.isEmpty()){
                in2Out();
            }
            return outStack.pop();
        }

        public int peek() {
            if(outStack.isEmpty()){
                in2Out();
            }
            return outStack.peek();
        }

        public boolean empty() {
            return inStack.isEmpty() && outStack.isEmpty();
        }

        private void in2Out(){
            while (!inStack.isEmpty()){
                outStack.push(inStack.pop());
            }
        }

    }

}
